package de.upb.messerschmidt.set;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.upb.messerschmidt.set.entity.Event;
import de.upb.messerschmidt.set.entity.Location;
import de.upb.messerschmidt.set.entity.Person;
import de.upb.messerschmidt.set.entity.Room;
import de.upb.messerschmidt.set.entity.Talk;
import de.upb.messerschmidt.set.jdo.PMF;

/**
 * Gets a {@link Talk}'s data via an HttpPost and persists it.
 * 
 * @author Tim Messerschmidt
 * 
 */
public class RegisterTalkServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String eventString = req.getParameter("event");
		String roomString = req.getParameter("room");
		String roomParam = roomString.split(" ")[0];
		String dateString = req.getParameter("date");
		String speakerString = req.getParameter("speaker");
		String topic = req.getParameter("topic");
		String description = req.getParameter("description");
		String timeFrom = req.getParameter("timeFrom");
		String timeTo = req.getParameter("timeTo");

		if (eventString == null || roomString == null || dateString == null
				|| speakerString == null || topic == null
				|| description == null || timeFrom == null || timeTo == null) {
			resp.setStatus(400);
			resp.getWriter().println("Please fill in all fields");
		} else {
			// Try to set the 2 dates;
			Date from = null;
			Date to = null;

			SimpleDateFormat sdfToDate = new SimpleDateFormat("dd.MM.yyyy H:m");

			try {
				from = sdfToDate.parse(dateString + " " + timeFrom);
				to = sdfToDate.parse(dateString + " " + timeTo);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			if (from != null && to != null) {
				// Try to get the right event
				String eventName = eventString.split(":")[0];
				Event event = null;

				PersistenceManager pm = PMF.get().getPersistenceManager();

				Query query = pm.newQuery(Event.class);
				query.setFilter("title == titleParam");
				query.declareParameters("String titleParam");
				query.setOrdering("title desc");

				try {
					List<Event> results = (List<Event>) query
							.execute(eventName);
					if (!results.isEmpty()) {
						event = results.get(0);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				Query personQuery = pm.newQuery(Person.class);
				personQuery
						.setFilter("name == nameParam && prename == prenameParam");
				personQuery
						.declareParameters("String nameParam, String prenameParam");
				personQuery.setOrdering("name desc");

				Person speaker = null;
				String[] name = nameParser(speakerString);

				List<Person> persons = (List<Person>) personQuery.execute(
						name[0], name[1]);

				if (!persons.isEmpty()) {
					speaker = persons.get(0);
				}

				if (speaker != null && event != null) {
					Query locationQuery = pm.newQuery(Location.class);
					locationQuery.setFilter("name == locationName");
					locationQuery.declareParameters("String locationName");

					List<Location> results = (List<Location>) locationQuery
							.execute(event.getLocation());

					if (!results.isEmpty()) {
						Location result = results.get(0);

						ArrayList<Room> rooms = result.getRooms();
						Room room = null;

						for (Room r : rooms) {
							if (r.getRoomNr().equals(roomParam))
								room = r;
						}

						if (room != null && speaker != null) {
							Talk talk = new Talk(event.getTitle(), from, to,
									speaker.getPrename() + " "
											+ speaker.getName(), topic,
									description, room.getRoomNr());

							event.getTalks().add(talk.getTopic());

							try {
								pm.makePersistent(talk);
								pm.refresh(event);
								pm.flush();

								resp.setStatus(200);
								resp.getWriter().println(
										"Talk registered successfully");
							} catch (Exception e) {
								e.printStackTrace();
								resp.setStatus(400);
								resp.getWriter().println(
										"Error when trying to save talk");
							} finally {
								pm.close();
							}
						}
					}
				}
			}
		}
	}

	private String[] nameParser(String user) {
		return user.split(", ");
	}
}
